Hãy nói rằng tôi có những mẫu bí danh:Lỗi thay thế có phải là lỗi với các tham số mẫu không phụ thuộc không?
enum class enabler {};
template <typename T>
using EnableIf = typename std::enable_if<T::value, enabler>::type;
template <typename T>
using DisableIf = typename std::enable_if<!T::value, enabler>::type;
tôi có thể làm như sau trong GCC:
#include <iostream>
template <typename T, EnableIf<std::is_polymorphic<T>> = {}>
void f(T) { std::cout << "is polymorphic\n"; }
template <typename T, DisableIf<std::is_polymorphic<T>> = {}>
void f(T) { std::cout << "is not polymorphic\n"; }
struct foo { virtual void g() {} };
int main() {
f(foo {});
f(int {});
}
It in:
là đa hình
không phải là đa hình
Điều phù hợp với mong đợi của tôi.
Với mật mã không biên dịch. Nó tạo ra các thông báo lỗi sau.
test.cpp:11:58: error: expected expression
template <typename T, EnableIf<std::is_polymorphic<T>> = {}>
^
test.cpp:14:59: error: expected expression
template <typename T, DisableIf<std::is_polymorphic<T>> = {}>
^
test.cpp:20:3: error: no matching function for call to 'f'
f(foo {});
^
test.cpp:12:6: note: candidate template ignored: couldn't infer template argument ''
void f(T) { std::cout << "is polymorphic\n"; }
^
test.cpp:15:6: note: candidate template ignored: couldn't infer template argument ''
void f(T) { std::cout << "is not polymorphic\n"; }
^
test.cpp:21:3: error: no matching function for call to 'f'
f(int {});
^
test.cpp:12:6: note: candidate template ignored: couldn't infer template argument ''
void f(T) { std::cout << "is polymorphic\n"; }
^
test.cpp:15:6: note: candidate template ignored: couldn't infer template argument ''
void f(T) { std::cout << "is not polymorphic\n"; }
^
4 errors generated.
Nó có nên biên dịch không? Trình biên dịch nào trong số hai trình biên dịch bị lỗi?
Rất tiếc, tôi cảm thấy ngớ ngẩn. Tôi có cảm giác điều này không liên quan gì đến bí danh mẫu, vì vậy tiêu đề có thể gây hiểu nhầm: S Xin lỗi về điều đó, tôi sẽ điều tra một chút và sửa tiêu đề nếu điều đó xảy ra. –
'DisableIf> = {}' là khởi tạo danh sách khởi tạo hợp pháp chưa? Cấu trúc có thể là các tham số giá trị mẫu không? –
jpalecek
@jpalecek Không, cấu trúc không thể. Đó là lý do tại sao tôi sử dụng một enum :) –