【发布时间】:2013-04-25 04:51:56
【问题描述】:
这更像是一个 c++ 标准问题。 考虑以下代码:
template <typename T>
class has_Data
{
typedef char one;
typedef long two;
template <typename C> static one test( typeof(&C::Data) ) ;
template <typename C> static two test(...);
public:
enum { value = sizeof(test<T>(0)) == sizeof(char) };
};
class MyClass {
private:
struct Data {
};
};
void function(bool val = has_Data<MyClass>::value) {}
以上代码适用于gcc (GCC) 4.4.3
但是clang version 3.3 (2545b1d99942080bac4a74cda92c620123d0d6e9) (2ff97832e593926ea8dbdd5fc5bcf367475638a9)
它给出了这个错误:
test_private_data.cpp:7:54: error: 'Data' is a private member of 'MyClass'
template <typename C> static one test( typeof(&C::Data) ) ;
^
/devshared/home/rhanda/test_private_data.cpp:7:37: note: while substituting explicitly-specified template arguments into function template 'test'
template <typename C> static one test( typeof(&C::Data) ) ;
^
/devshared/home/rhanda/test_private_data.cpp:21:26: note: in instantiation of template class 'has_Data<MyClass>' requested here
void function(bool val = has_Data<MyClass>::value) {}
^
1 error generated.
哪个是对的?
从标准文档 (n3485) 中,我发现了一个似乎比 gcc 更同意 clang 的声明。
访问控制统一应用于所有名称,无论名称是从声明还是表达式中引用。
【问题讨论】:
-
您的意思是
template <typename C> static one test( typename C::Data * );?我只是好奇decltype( &C::Data )为你做了什么…… -
它是一样的..只是检测函数是否可以解析为第一个函数..如果我改变使用你的代码..它做同样的事情,我想。
-
@RamneekHanda
decltype( &C::Data )不是type of pointer to a data-member C::Data吗?因为,如果您确实按照所示运行测试,function()参数val是0。你不是说要1换成MyClass吗? -
请注意,
typeof不是 C++ 标准的一部分,它是 GCC 扩展。