2016-09-05 60 views
2

当我们通过一(多)派生类模板函数期待基类什么是模板实例规则?例如:模板实例有多个模板继承

#include <iostream> 

template <int x> 
struct C {}; 

struct D : C<0>, C<1> {}; 

template <int x> 
void f (const C<x> &y) { std::cout << x << "\n"; } 

int main() 
{ 
    f (D()); 
} 

MSVC 2015打印0,铛3.8 - 1和gcc 6.2给出编译器错误(Demo)。而且,即使你SFINAE-了所有重载除一人外,结果仍然是不同的:

#include <iostream> 

template <int x> struct C {}; 

template<> 
struct C<0> { using type = void; }; 

struct D : C<0>, C<1> {}; 

template <int x, typename = typename C<x>::type> 
void f (const C<x> &y) { std::cout << x << "\n"; } 

int main() 
{ 
    f (D()); 
} 

现在只编译与MSVC,如果你换C<0>C<1>只铛会编译它。问题在于MSVC只尝试实例化第一个base,clang - last和gcc打印错误太早。哪个编译器是正确的?

+0

在我看来,好像它们都是错的。它不应该是一个模糊的函数调用吗? –

+0

*“MSVC打印0,铛-1和gcc给编译器错误。”*,哪个MSVC,哪个gcc和哪个铛? –

+0

@PiotrSkotnicki新增版本号,但它们都具有相同的行为 –

回答

1

GCC 5.4:

/tmp/gcc-explorer-compiler11685-58-1h67lnf/example.cpp: In function 'int main()': 
13 : error: no matching function for call to 'f(D)' 
f (D()); 
^ 
9 : note: candidate: template<int x> void f(const C<x>&) 
void f (const C<x> &y) { std::cout << x << "\n"; } 
^ 
9 : note: template argument deduction/substitution failed: 
13 : note: 'const C<x>' is an ambiguous base class of 'D' 
f (D()); 
^ 
Compilation failed 

这在我看来是正确的结果,因为C < 0>和C < 1>同样专业。

海合会6.2

铛3.8.1同样的结果编译它,这在我看来是一个编译器错误。

更新:

我不知道实际的使用情况,但我不知是否会为你工作:

#include <utility> 
#include <iostream> 

template<class T> 
struct has_type 
{ 
    template<class U> static auto test(U*) -> decltype(typename U::type{}, std::true_type()); 
    static auto test(...) -> decltype(std::false_type()); 
    using type = decltype(test((T*)0)); 
    static const auto value = type::value; 
}; 

template <int x> struct C {}; 

template<> 
struct C<0> { using type = int; }; 

template<int...xs> 
struct enumerates_C : C<xs>... 
{ 
}; 

struct D : enumerates_C<0, 1> {}; 

template<int x, std::enable_if_t<has_type<C<x>>::value>* = nullptr> 
void f_impl(const C<x>& y) 
{ 
    std::cout << x << "\n"; 
} 

template<int x, std::enable_if_t<not has_type<C<x>>::value>* = nullptr> 
void f_impl(const C<x>& y) 
{ 
    // do nothing 
} 

template <int...xs> 
void f (const enumerates_C<xs...> &y) 
{ 
    using expand = int[]; 
    void(expand { 0, 
     (f_impl(static_cast<C<xs> const &>(y)),0)... 
    }); 
} 

int main() 
{ 
    f (D()); 
} 

预期输出(苹果铛测试):

0 
+0

在第一个例子中 - 是的,我认为它应该是模棱两可的,第二个 - 不,只应该启用C <0>的超载。 –

+0

“*仅适用于C <0>应该启用*”您认为编译器应该尝试使用每个可能的'x'是什么原因?第一个扣除发生,其中失败 –

+0

@PiotrSkotnicki我问这个问题,以了解它应该如何完成。如果手动写这个功能,那么它会工作打算: https://gist.github.com/telishev/a52483833ae6850df69e1e6953f6b277 –