如何专门化模板类方法基于类型特征?使用std::enable_if对非类函数有效,但对类方法无效
How to specialize templated class methods based on type traits? Using std::enable_if works for non-class functions, but fails for class methods
我一直在尝试创建模板化类方法的特化,这样我就会有不同的方法定义,编译器根据参数是否为枚举类的整型选择,但是clang给了我这个错误:
'ParseString'的越行定义与'MyData'中的任何声明不匹配
而GCC给出如下:
下面的代码用于产生这些错误。我已经尝试了使用错误:原型'typename std::enable_if::value, void>::type MyData::ParseString(T&, std::string)'不匹配任何类'MyData'
错误:候选人是:模板静态无效MyData::ParseString(T&, std::string)
enable_if
的其他方法,比如在模板参数中而不是返回类型中,但到目前为止都没有效果。如果我将模板化的函数设置为非类函数而不是类方法,那么它们就可以正常工作。(去除静电没有影响)
是否有一种方法可以使用enable_if
模板化类方法,或者更好的方法来实现同样的事情?
#include <string>
#include <type_traits>
#include <utility>
class MyData
{
public:
MyData() = default;
MyData(std::pair<std::string, std::string> string_representations);
std::pair<std::string, std::string> ToStrings();
enum class MyEnum
{
A = 0,
B = 1
};
int integral_value;
MyEnum enum_value;
private:
template<typename T>
static void ParseString(T&, std::string);
};
MyData::MyData(std::pair<std::string, std::string> string_representations)
{
ParseString(integral_value, string_representations.first);
ParseString(enum_value, string_representations.second);
}
std::pair<std::string, std::string> MyData::ToStrings()
{
return std::make_pair(std::to_string(integral_value), std::to_string((unsigned long)enum_value));
}
template<typename T>
typename std::enable_if<std::is_enum<T>::value, void>::type
MyData::ParseString(T& setting, std::string representation)
{
setting = (T)std::stoul(representation);
}
template<typename T>
typename std::enable_if<std::is_integral<T>::value, void>::type
MyData::ParseString(T& setting, std::string representation)
{
setting = std::stoi(representation);
}
(在本例中,该类只有一个整型和一个枚举成员,但如果您想知道为什么模板化函数会有用,请想象一下,如果该类有多个不同的枚举和整型成员。)
这个错误告诉你,你的ParseString
方法定义中的签名不匹配类内部声明中的签名。您必须复制enable_if
并在声明中使用它。
template<typename T>
static typename std::enable_if<std::is_integral<T>::value, void>::type ParseString(T&, std::string);
您还需要另一个在声明中使用enable_if<is_enum<T>>
的ParseString
声明,因为您定义了另一个使用它的函数:
template<typename T>
static typename std::enable_if<std::is_enum<T>::value, void>::type ParseString(T&, std::string);
相关文章:
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 在静态库中嵌入类方法
- 如何制作一个将函数作为参数的类方法
- 从父类方法返回子类对象
- 使用用户定义的参数调用future/async并调用类方法
- 重载类方法的不明确调用
- 单独定义模板化嵌套类方法的正确语法
- 绑定派生类方法C++从实例范围之外的分隔 std::function 变量调用
- 如何访问由共享指针保存的类方法?
- 将子类方法声明为基类的友元
- 我的模板类方法返回错误类型?
- Qt将信号与另一个类方法连接
- 我无法使用C++指针指向类方法返回的 std::vector
- 如何在成为指向基类的指针后保留对子类方法的使用?
- 检查类方法中是否(此 == nullptr)
- 从基类实例调用派生类方法而不进行强制转换
- 函数从唯一代码调用正确的子类方法
- C++ - 如何在不静态的情况下将回调绑定到类方法?
- C++ |DLL / EXE - 如何从导出的类调用另一个类方法?
- 用 c++ 编写一堆类似的 if 语句的漂亮方法