未定义类型的重载
Overload for undefined type
我正在尝试对模板函数进行一些重载,以下是的示例
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());
}
相关文章:
- 从父命名空间重载类型
- 如何确保接受的C++模板类型使运算符重载?
- 模板化类如何解析在其类型之一上调用的重载非成员函数?
- 错误:表达式必须具有算术、无作用域枚举或带有运算符重载的指针类型
- 泛型枚举和其他类型的重载模板函数
- 避免在人为的重载函数调用中拼写出类型
- 为什么重载运算符可以返回其返回类型以外的其他内容?
- 为什么在传递长整型时调用具有两个双精度类型的参数的重载函数?
- 重载模板函数未为特定类型选择正确的版本
- 如何为流输出运算符提供重载<<模板'using'类型别名?
- MSVC 错误:4 个重载中的任何一个都无法转换所有参数类型
- 具有重载类型转换运算符的函数对象崩溃
- 为什么在指定重载类型的返回值时出现编译错误
- 忽略C++重载类型转换运算符
- 重载 C++ 类型以处理自定义类
- 重载类型强制转换运算符,以强制转换为指向函数的指针
- C++中的一元运算符重载类型(新手)
- 函数不能在模板实例中推导出重载类型
- 重载类型转换运算符的语法
- 重载 C++ 类型转换(函数)