c++ - 成员函数 SFINAE 错误 C2938

标签 c++ visual-c++ sfinae

此代码在 VS2013 中编译失败。

template<typename T>
class SomeClass {
public:
    std::enable_if_t<std::is_fundamental<T>::value, T>
        DoSomething() {
        return T();
    }

    std::enable_if_t<!std::is_fundamental<T>::value, T>
        DoSomething() {
        return T();
    }
};

如何在VS2013中实现(DoSomething必须是非静态成员函数)?

最佳答案

SFINAE 仅适用于模板。您的 DoSomething() 不是模板,它是类模板的非模板成员。您需要将其设为模板:

template<typename T>
class SomeClass {
public:
    template <class U = T>
    std::enable_if_t<std::is_fundamental<U>::value, T>
        DoSomething() {
        return T();
    }

    template <class U = T>
    std::enable_if_t<!std::is_fundamental<U>::value, T>
        DoSomething() {
        return T();
    }
};

[Live example]

关于c++ - 成员函数 SFINAE 错误 C2938,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28043532/

相关文章:

c++ - 使用 SFINAE 在 C++ 中强制类型转换

c++ - 我如何为 std::string 专门化我的模板

c++ - 如何为 STL 类容器提供公共(public) const 迭代器和私有(private)非 const 迭代器?

c++ - 我们可以通过哪些不同的方式动态链接 DLL

c++ - 如何将屏幕图像放入内存缓冲区?

c++ - 如何使用大 vector 初始化来避免 "compiler limit: compiler stack overflow"?

C++ - 如何创建具有 4 个变量和 4 个键的多重映射

c++ - 使用 SFINAE 检查类是否相同或派生自 C++98 中的另一个模板类

c++ - 从 eeprom 接收数据时程序崩溃

c++ - 我可以用什么代替 std::move()?