IMO,C++模板规则似乎限制太多,并且定义了编译器实现.但在这里,我有一个特定的行为,我很难缠绕我的脑袋.
在下面的问题中,我有意识地避免明确地专门化父类.
问题是,我可以部分专门化一个成员,但不能完全专门化.这实际上是反直觉的,因为您可以轻松地将虚拟模板添加到完全专用的模板中并使其部分专用.这里发生了什么??
重要的编辑:这很重要,因为,正如我们所知,你不能专门化成员函数而不专门化这个类(可以看作是这个问题的组合,需要部分专业化,而且c ++没有允许部分专门的函数.我不知道这些函数是否相关,但至少它们是一致的),因此如果你想在你的班级中使用一个你可以专攻的函数,你就会被使用仿函数所困扰.最重要的是,你需要添加一个虚拟模板参数,以使其工作!
这有效:
template <class T>
class A
{
template<typename Y, typename Z>
struct C{
void operator()(int x);
};
template<typename Z>
struct C<int, Z>{
void operator()(int x);
};
};
template <class T>
template <typename Z>
void A<T>::C<int, Z>::operator()(int x){
}
Run Code Online (Sandbox Code Playgroud)
但这不是:
template <class T>
class A
{
template<typename Y>
struct C{
void operator()(int x);
};
template<>
struct C<int>{
void operator()(int x);
};
};
template <class T>
template <>
void A<T>::C<int>::operator()(int x){
}
Run Code Online (Sandbox Code Playgroud)
编辑:Sean F.在评论中指出,编译器很难选择专业化.但问题在于,部分专业化不会使问题消失.所以这不是答案.
c++ templates partial-specialization rationale template-specialization
我最近注意到一个奇怪的事情,Tensorflow在使用常量初始化变量时似乎使用了太多内存.有人可以帮我理解下面的例子吗?
$ python -m memory_profiler test.py
[0 1 2 3 4 5 6 7 8 9]
Filename: test.py
Line # Mem usage Increment Line Contents
================================================
4 144.531 MiB 0.000 MiB @profile
5 def go():
6 907.312 MiB 762.781 MiB a = np.arange(100000000)
7 910.980 MiB 3.668 MiB s = tf.Session()
8 1674.133 MiB 763.152 MiB b = tf.Variable(a)
9 3963.000 MiB 2288.867 MiB s.run(tf.variables_initializer([b]))
10 3963.145 MiB 0.145 MiB print(s.run(b)[:10])
Run Code Online (Sandbox Code Playgroud)