clang不编译我的代码,但是g++编译
clang does not compile my code, but g++ does
有人能帮我处理这个代码吗:
#include <type_traits>
#include <vector>
struct nonsense { };
template <struct nonsense const* ptr, typename R>
typename std::enable_if<!std::is_void<R>::value, int>::type
fo(void* const)
{
return 0;
}
template <struct nonsense const* ptr, typename R>
typename std::enable_if<std::is_void<R>::value, int>::type
fo(void* const)
{
return 1;
}
typedef int (*func_type)(void*);
template <std::size_t O>
void run_me()
{
static struct nonsense data;
typedef std::pair<char const* const, func_type> pair_type;
std::vector<pair_type> v;
v.push_back(pair_type{ "a", fo<&data, int> });
v.push_back(pair_type{ "b", fo<&data, void> });
}
int main(int, char*[])
{
run_me<2>();
return 0;
}
clang-3.3没有编译这个代码,但g++-4.8.1编译了,两个编译器中哪一个是对的?正如我所怀疑的,代码有问题吗?
错误显示:
a.cpp:32:15: error: no matching constructor for initialization of 'pair_type' (aka 'pair<const char *const, func_type>')
v.push_back(pair_type{ "a", fo<&data, int> });
^ ~~~~~~~~~~~~~~~~~~~~~~~
a.cpp:33:15: error: no matching constructor for initialization of 'pair_type' (aka 'pair<const char *const, func_type>')
v.push_back(pair_type{ "b", fo<&data, void> });
^ ~~~~~~~~~~~~~~~~~~~~~~~~
将static struct nonsense data
重新定位到函数外将获得要编译的代码。我不够精明,无法告诉你原因。
要为O
参数的不同值定制data
,可以如下定义nonsense
…
template <size_t> struct nonsense {
static nonsense data;
⋮
};
…并因此使用它…
template <std::size_t O, typename R>
typename std::enable_if<!std::is_void<R>::value, int>::type
fo(void* const)
{
// Use nonsense<O>::data
}
template <std::size_t O, typename R>
typename std::enable_if<std::is_void<R>::value, int>::type
fo(void* const)
{
// Use nonsense<O>::data
}
⋮
template <std::size_t O>
void run_me()
{
std::vector<std::pair<char const* const, func_type>> v;
v.emplace_back("a", fo<O, int >);
v.emplace_back("b", fo<O, void>);
}