[编辑:
以下适用于我的机器上的 g++ 4.9.0 和 clang 3.5:
template<class T>
struct dummy {};
template<class T>
struct A {
private:
template<class U>
struct AConstructor {
static void construct(A<T>* thisPtr) {
thisPtr->foo = 42;
}
};
template<class>
friend class AConstructor;
public:
template<class U>
A(dummy<U>) {
AConstructor<U>::construct(this);
}
void print() const {
std::cout << foo << std::endl;
}
private:
int foo;
};
int main() {
A<void> foobar( (impl::dummy<void>()) );
foobar.print();
return 0;
}
]
对我来说,这是:
template<class T>
struct A; //forward declaration
namespace impl {
template<class T>
struct wrap {
template<class U>
struct AConstructor {
static void construct(A<T>* thisPtr) {
thisPtr->foo = 42;
}
};
//some partial specialization...
};
template<class T>
struct dummy{};
} //end of namespace
template<class T>
struct A {
template<class>
friend class impl::wrap<T>::AConstructor;
template<class U>
A(impl::dummy<U>) {
impl::template wrap<T>::template AConstructor<U>::construct(this);
}
void print() const {
std::cout << foo << std::endl;
}
private:
int foo;
};
int main() {
A<void> foobar( (impl::dummy<void>()) );
foobar.print();
return 0;
}
使用 g++ 4.9.0 编译并按预期工作(它在标准输出上显示 42)虽然编译失败并使用 clang 3.5,我想说这是一个 clang 错误,但我必须承认我不太确定那个。
不过,如果是这种情况,您会发现这很有用:
Class template with template class friend, what's really going on here?
Template friend
但是,我不太喜欢这种设计,你确定你真的需要构造函数的部分专业化吗?您不能使用 SFINAE 丢弃它们,或者使用 trait 类访问某些子类型(或任何其他您想要部分专业化的东西,可以用其他东西代替)?
例如以下结构之一:
#include <list>
#include <vector>
template<class T>
struct is_vector : std::false_type {};
template<class T>
struct is_vector<std::vector<T>> : std::true_type {};
struct A {
template<
class T, typename std::enable_if<is_vector<T>::value, void*>::type = nullptr
>
A(T) {
std::cout << "construction with a vector" << std::endl;
}
template<class T>
A(std::list<T>) {
std::cout << "construction with a list of " << typeid(T).name();
std::cout << std::endl;
}
template<
class T,
typename std::enable_if<!is_vector<T>::value, void**>::type = nullptr
>
A(T) {
std::cout << "construction with an iterator (supposedly) whose value_type "
"is";
std::cout << typeid(typename std::iterator_traits<T>::value_type).name();
std::cout << std::endl;
}
};
int main() {
A(std::vector<int>());
A(std::list<std::vector<int>>());
A((char*) nullptr);
return 0;
}
在我的机器上显示这个:
用向量构造
使用 NSt3__16vectorIiNS_9allocatorIiEEEE 列表构造
使用其 value_type 为 c 的迭代器(假设)构造
(当然我不知道你想做什么,所以我不确定,我会对此发表评论而不是将其放在答案中,但我没有足够的声誉去做所以,今天创建了帐户)