gpt4 book ai didi

c++ - “使用”声明为 SFINAE

转载 作者:可可西里 更新时间:2023-11-01 18:28:06 25 4
gpt4 key购买 nike

我可以使用 SFINAE(或其他技术)在 using 声明的同时从模板类派生 private 吗?为了更好地理解,请参阅下面的代码:

#include <iostream>

struct S1 {
void f() { std::cout << "S1::f\n"; }
};

struct S2 {
void f() { std::cout << "S2::f\n"; }
void g() { std::cout << "S2::g\n"; }
};

template <class T>
struct D : private T {
using T::f;
// using T::g; // need this only if T provides g() function
};

int main() {
D<S1>().f(); // ok. Prints 'S1::f'
D<S2>().f(); // ok. Prints 'S2::f'
D<S2>().g(); // fail. But wants to be ok and prints 'S2::g'
return 0;
}

我怎样才能达到期望的行为(如果可能的话)?

最佳答案

Bryan Chen 的答案变体看起来更丑陋,但更容易扩展到多个检查,并且不需要复制 D<type-with-f> 之间共享的代码和 D<type-without-f> , 是使用继承链,其中每个步骤检查一个额外的成员。如果合适,唯一需要的复制是构造函数的继承。

struct A {
void f() { }
void g() { }
void i() { }
};

// The generic case. D<T, char[N]> simply provides what D<T, char[N+1]> provides.
template <typename T, typename U = char[1]>
struct D : D<T, char[sizeof(U) + 1]> {
using D<T, char[sizeof(U) + 1]>::D;
};

// The end of the chain. This is where T gets inherited. It declares all of its own
// specialisations as its friends, so that they can access other members of T.
template <typename T>
struct D<T, char[6]> : private T {
template <typename, typename>
friend struct D;

D(int) { }
void fun() { }
};

// Check for T::f.
template <typename T>
struct D<T, char[2 + !sizeof(&T::f)]> : D<T, char[3]> {
using D<T, char[3]>::D;
using T::f;
};

// Check for T::g.
template <typename T>
struct D<T, char[3 + !sizeof(&T::g)]> : D<T, char[4]> {
using D<T, char[4]>::D;
using T::g;
};

// Check for T::h.
template <typename T>
struct D<T, char[4 + !sizeof(&T::h)]> : D<T, char[5]> {
using D<T, char[5]>::D;
using T::h;
};

// Check for T::i.
template <typename T>
struct D<T, char[5 + !sizeof(&T::i)]> : D<T, char[6]> {
using D<T, char[6]>::D;
using T::i;
};

int main() {
D<A> d = 4; // ok: verify that constructors got inherited
// A &a = d; // error: verify that inheritance of A is private
d.f(); // ok: verify that f got inherited
d.g(); // ok: verify that g got inherited
// d.h(); // error: verify that h is not available
d.i(); // ok: verify that i got inherited
d.fun(); // ok: verify that the inheritance chain didn't get broken
}

注意:而不是检查 &T::f , 你可能想用 std::declval<T>().f() 做点什么反而。前者无法处理重载函数。

关于c++ - “使用”声明为 SFINAE,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28232730/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com