2012-12-20 24 views
3

是否可以将is_const表达式转换为test函数,或者这是不可能的,因为顶级cv-qualifieres在模板类型推理期间被忽略?is_const <func-param> in函数模板总是返回false

int main() 
{ 
    using std::is_const; 

    const int x = 0; 
    int y = 0; 

    // move to "bool test()" 
    std::cout 
    << "main, x: " << is_const<decltype(x)>::value << "\n" // true 
    << "main, y: " << is_const<decltype(y)>::value << "\n" // false 
    ; 

    std::cout 
    << "test, x: " << test(x) << "\n" // false, I wanted true 
    << "test, y: " << test(y) << "\n" // false 
    ; 
} 

我已经尝试过失败类似于各种版本:我想确保我不缺少的东西,并且写这样一个test功能确实不可能

template<typename T> 
bool test(T x) 
{ 
    return is_const<???>::value; 
} 

。 (如果有可能,我也想知道C++ 03版本是否是可能的。)

谢谢您的考虑

更新

由于Mankarse我了解到型扣在右值引用的情况不同:

template<typename T> void t1(T x); 
template<typename T> void t2(T& x); 
template<typename T> void t3(T&& x); 

const int x = 42; 
int y = 0; 

t1(x); // T = int:  t1<int>(int x) 
t1(y); // T = int:  t1<int>(int x) 

t2(x); // T = const int: t2<const int>(const int& x) 
t2(y); // T = int: t2<int>(int& x) 

t3(x); // T = const int&: t3<const int&>(const int& && x) 
t3(y); // T = int&:  t3<int&>(int& && x) 
+1

您的意思是'布尔测试(T && X )'完美转发? (如果模板函数的参数不是引用类型,则在确定其类型时不考虑顶级cv-qualifiers。) –

+0

'typename T :: value_type'? – maverik

回答

6

在C++ 11,这可以用完美转发右值引用来完成:

template<typename T> 
bool test(T&& x) 
{ 
    return std::is_const<typename std::remove_reference<T>::type>::value; 
} 

在C++ 03,可以改为使用左值参考:

template<typename T> 
bool test(T& x) { 
    return boost::is_const<T>::value; 
} 

两者之间的差异如下所示:

typedef int const intc; 
intc x = intc(); 
int y = int(); 
std::cout          // C++11 C++03 
    << "x: " << test(x) << "\n"     // 1  1 
    << "y: " << test(y) << "\n"     // 0  0 
    << "move(x): " << test(std::move(x)) << "\n"// 1  1 (when compiled as C++11) 
    << "move(y): " << test(std::move(y)) << "\n"// 0  compilation error 
    << "intc{}: " << test(intc()) << "\n"  // 0  compilation error 
    << "int{}: " << test(int()) << "\n"   // 0  compilation error 
;