![](/img/trans.png)
[英]`enable_if()` to disable static member function declaration of templated class
[英]Using member declaration with enable_if?
我需要使用成員聲明的條件。
template <bool> struct B;
template <> struct B<true> { void foo(); };
template <> struct B<false> { };
template <typename T>
struct A : public B<is_default_constructible<T>::value> {
using B<is_default_constructible<T>::value>::foo();
void foo(int) {}
};
這顯然不起作用,因為B<bool>::foo
在一半的情況下沒有定義。 我怎樣才能做到這一點? 要在foo(int)旁邊的A<T>
范圍內看到B<>::foo()
)?
感謝幫助
這是我的解決方案。 我相信它不會是最好的,但它可以完成工作。
struct A {
void foo(int) {}
};
struct A
應包含您希望在兩種情況下定義的方法。
template <bool> struct B;
template <> struct B<false> : A {};
template <> struct B<true> : A {
using A::foo;
void foo() {}
};
在B<false>
情況下,僅定義void foo(int)
。 在B<true>
情況下,定義了void foo(int)
和void foo()
。
template <typename T>
struct C : public B<is_default_constructible<T>::value> {};
現在我不必擔心在某些情況下沒有定義B<is_default_constructible<T>::value>::foo()
。
class D { D() = delete; };
int main()
{
C<int> c1;
c1.foo(1234);
c1.foo();
// both methods are defined for C<int>
C<D> c2;
c2.foo(1234);
// c2.foo(); // undefined method
return 0;
}
enable_if
不能用於此。 你也需要專門化struct A
#include <type_traits>
template <bool> struct B;
template <> struct B<true> { void foo(); };
template <> struct B<false> { };
template <typename T, bool default_constructible = std::is_default_constructible<T>::value>
struct A : public B<default_constructible> {
using B<default_constructible>::foo;
void foo(int) {}
};
template<typename T>
struct A<T, false> : public B<false> {
void foo(int) {}
};
如果foo(int)
在兩種情況下都具有相同的功能,您可能希望從另一個基礎結構派生它:
#include <type_traits>
template <bool> struct B;
template <> struct B<true> { void foo(); };
template <> struct B<false> { };
template<typename T>
struct C {
void foo(int) {}
};
template <typename T, bool default_constructible = std::is_default_constructible<T>::value>
struct A : public B<default_constructible>, public C<T> {
using B<default_constructible>::foo;
using C<T>::foo;
};
template<typename T>
struct A<T, false> : public B<false>, public C<T> {
using C<T>::foo;
};
最后,要從struct A
的模板參數中刪除該bool,您可能希望將選擇foo
重載的責任轉發給基類。 這也有一個好處,就是不要復制您可能想要添加的其他struct A
成員的代碼。
#include <type_traits>
template <bool> struct B;
template <> struct B<true> { void foo(); };
template <> struct B<false> { };
template<typename T>
struct C {
void foo(int) {}
};
template <typename T, bool default_constructible = std::is_default_constructible<T>::value>
struct base_A : public B<default_constructible>, public C<T> {
using B<default_constructible>::foo;
using C<T>::foo;
};
template<typename T>
struct base_A<T, false> : public B<false>, public C<T> {
using C<T>::foo;
};
template <typename T>
struct A : public base_A<T> {
// Other members.
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.