C++ type_traits 模板,如果不是 const,则添加引用

标签 c++ templates c++11 typetraits

我有一个接受类型 T 的类模板。它有一个方法。我希望此方法返回类型 T 如果它是 constT& 如果它是非 const

template<typename T>
class C
{
    static typename add_reference_if_non_const<T>::type method();
};

int main()
{
    assert( is_same<result_of<C<int>::method()>::type, int&>::value );
    assert( is_same<result_of<C<const int>::method()>::type, const int>::value );
}

我该怎么做?

最佳答案

你想要 C<int const>::method() 的返回类型成为int const , 但是 top-level cv qualifiers are ignored on function return types .无论如何,因为method()返回 T 的拷贝,你真的在​​乎你回来吗T const而不是 T

鉴于此,我认为您想要的是以下内容

using add_reference_if_non_const =
    typename std::conditional<std::is_const<T>{},
                              typename std::remove_const<T>::type,
                              typename std::add_lvalue_reference<T>::type
                >::type;
static add_reference_if_non_const method();

你可以替换typename std::remove_const<T>::typeT如果你想返回 T const什么时候T是一个类类型。


下一个问题是 result_of 适用于类型参数;您在问题中遇到的是 C::method 的函数调用.你需要使用

result_of<decltype(&C<int>::method)()>::type

但是因为你需要使用 decltype无论如何,你可以完全取消 result_of .

decltype(C<int>::method())

最后,你不需要 assert在运行时,您可以在编译时使用 static_assert 进行检查

static_assert( is_same<decltype(C<int>::method()),       int&>::value, "");
static_assert( is_same<decltype(C<int const>::method()), int>::value,  "" );

Live demo

关于C++ type_traits 模板,如果不是 const,则添加引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33199101/

相关文章:

c++ - 如何在 C++ 中将运行时类型鉴别器映射到模板实例(无需手动枚举它们)?

c++ shared_ptr 从 char* 到 void*

c++ - Objective-C 还是 C++?

c++ - 从非模板化接口(interface)检索 'generic'数据

c++ - 使用 using 捕获模板化可调用对象的返回类型

c++ - 命名空间的 Boost.Log 错误

c++ - 为什么此代码无法使用 gcc 4.8.5 进行编译,而使用 clang 可以正常编译

c++ - 编程 Arduino 与标准 C 有何不同?

C++ 数组输入和退出验证

c++ - 如何只设置一个存在的成员?