未定义类型的重载

Overload for undefined type

本文关键字:重载 类型 未定义      更新时间:2023-10-16

我正在尝试对模板函数进行一些重载,以下是的示例

do_something.h

template<typename T>
void do_something(T const &input){/*....*/}
void do_something(std::string const &input);
void do_something(boost::container::string const &input);

到目前为止,还不错,但是如果我想重载一个未定义的类型呢?

类似于使用类型CCD_ 1没有在头文件中定义

void do_something(some_type const &input);

我想像这个一样使用它

main.cpp

#include "do_something.h"
#include "some_type.h"
#include <boost/container/string.hpp>
int main()
{
     do_something(std::string("whatever"));
     do_something(boost::container::string("whatever"));
     //oops, some_type() never defined in the header file, this
     //function will call the template version, but this is not
     //the behavior user expected
     do_something(some_type());   
}

由于some_type不是POD,也不是std::string,因此boost::container::string。我想我可以设计一个特性来进行一些编译时检查

template<typename T>
typename boost::enable_if<is_some_type<T>::value, T>::type
do_something(T const &input){//.....}

但是我有更好的方法吗?

我需要编译时类型检查,所以我使用模板。所有调用此函数的类型都会根据不同的类型执行类似的工作,所以我更喜欢重载。我不需要保存状态,所以我更喜欢函数而不是类。希望这能帮助你更多地了解我的意图。谢谢

但是如果我想重载一个未定义的类型呢?

您需要提供的声明

void do_something(some_type const &input);

然后使用类型为some_type的对象调用do_something。否则,将使用模板版本。

#include "do_something.h"
#include "some_type.h"
// This is all you need. You can implement the function here
// or any other place of your choice.
void do_something(some_type const &input);
#include <boost/container/string.hpp>
int main()
{
     do_something(std::string("whatever"));
     do_something(boost::container::string("whatever"));
     //oops, some_type() never defined in the header file, this
     //function will call the template version, but this is not
     //the behavior user expected
     do_something(some_type());   
}