如何测试别名是否是D 2.0中的模板?
template isTemplate(alias T)
{
enum bool isTemplate = ???;
}
Run Code Online (Sandbox Code Playgroud)
更新:
它应该像:
struct S(T)
{
int opCall() { return 0; }
int opUnary(string s)() if (s == "-") { return 0; }
}
pragma(msg, isTemplate!(S)); //Should print true
pragma(msg, isTemplate!(S!(int))); //Should print false
pragma(msg, isTemplate!((S!(int)).opCall)); //Should print false
pragma(msg, isTemplate!((S!(int)).opUnary)); //Should print true
Run Code Online (Sandbox Code Playgroud)
作为参考,事情不工作:
你不能使用任何表达式,T!(...)因为你不知道要用什么代替省略号.
你不能说&T因为如果你只是给了一个普通的旧类型名称,这也行不通.
除了我在另一个答案中列出的2个测试外,这通过了所有测试
import std.algorithm : startsWith, canFind;
template isTemplate(alias B) {
enum isTemplate = !__traits(compiles, {auto x=B;}) // excludes values
&& !__traits(compiles, {B x;}) // excludes types
&& __traits(compiles, {alias B x;}) // excludes instance members
&& !B.stringof.startsWith("module ", "package ") // excludes modules
&& !B.stringof.canFind("!("); // excludes instantiated templates
}
Run Code Online (Sandbox Code Playgroud)
2个失败的测试如下:
struct Inner2(string U="!(") {}
static assert(isTemplate(Inner2));
Run Code Online (Sandbox Code Playgroud)
如果您确定模板没有包含的默认参数,"...!(..."我认为它是安全的.
| 归档时间: |
|
| 查看次数: |
261 次 |
| 最近记录: |