@@ -1845,44 +1845,51 @@ $(H3 $(GNAME compiles))
1845
1845
compile (are semantically correct).
1846
1846
The arguments can be symbols, types, or expressions that
1847
1847
are syntactically correct.
1848
- The arguments cannot be statements or declarations.
1848
+ The arguments cannot be statements or declarations - instead
1849
+ these can be wrapped in a $(DDSUBLINK spec/expression, function_literals,
1850
+ function literal) expression.
1849
1851
)
1850
1852
1851
1853
$(P If there are no arguments, the result is $(D false).)
1852
1854
1853
1855
$(SPEC_RUNNABLE_EXAMPLE_COMPILE
1854
1856
---
1855
- import std.stdio;
1857
+ static assert(!__traits(compiles));
1858
+ static assert(__traits(compiles, 1 + 1)); // expression
1859
+ static assert(__traits(compiles, typeof(1))); // type
1860
+ static assert(__traits(compiles, object)); // symbol
1861
+ static assert(__traits(compiles, 1, 2, 3, int, long));
1862
+ static assert(!__traits(compiles, 3[1])); // semantic error
1863
+ static assert(!__traits(compiles, 1, 2, 3, int, long, 3[1]));
1864
+
1865
+ enum n = 3;
1866
+ // wrap a declaration/statement in a function literal
1867
+ static assert(__traits(compiles, { int[n] arr; }));
1868
+ static assert(!__traits(compiles, { foreach (e; n) {} }));
1856
1869
1857
1870
struct S
1858
1871
{
1859
1872
static int s1;
1860
1873
int s2;
1861
1874
}
1862
1875
1876
+ static assert(__traits(compiles, S.s1 = 0));
1877
+ static assert(!__traits(compiles, S.s2 = 0));
1878
+ static assert(!__traits(compiles, S.s3));
1879
+
1863
1880
int foo();
1864
- int bar();
1865
1881
1866
- void main()
1867
- {
1868
- writeln(__traits(compiles)); // false
1869
- writeln(__traits(compiles, foo)); // true
1870
- writeln(__traits(compiles, foo + 1)); // true
1871
- writeln(__traits(compiles, &foo + 1)); // false
1872
- writeln(__traits(compiles, typeof(1))); // true
1873
- writeln(__traits(compiles, S.s1)); // true
1874
- writeln(__traits(compiles, S.s3)); // false
1875
- writeln(__traits(compiles, 1,2,3,int,long,std)); // true
1876
- writeln(__traits(compiles, 3[1])); // false
1877
- writeln(__traits(compiles, 1,2,3,int,long,3[1])); // false
1878
- }
1882
+ static assert(__traits(compiles, foo));
1883
+ static assert(__traits(compiles, foo + 1)); // call foo with optional parens
1884
+ static assert(!__traits(compiles, &foo + 1));
1879
1885
---
1880
1886
)
1881
1887
1882
1888
$(P This is useful for:)
1883
1889
1884
1890
$(UL
1885
- $(LI Giving better error messages inside generic code than
1891
+ $(LI Giving better error messages (using $(DDSUBLINK spec/version, static-assert,
1892
+ `static assert`)) inside generic code than
1886
1893
the sometimes hard to follow compiler ones.)
1887
1894
$(LI Doing a finer grained specialization than template
1888
1895
partial specialization allows for.)
0 commit comments