我需要算法将大的静态大小的矩形分成小的矩形.对我来说完美的实现看起来像这样:
struct RECT
{
int l,t,r,b;
};
class BigRect
{
public:
// width and height of big rect
BigRect( unsigned width, unsigned height );
// returns -1 if rect cannot be allocated, otherwise returns id of found rect
int GetRect( unsigned width, unsigned height, RECT &out );
// returns allocated rect to big rectangle
void FreeRect( int id );
};
void test()
{
BigRect r( 10, 10 );
RECT out;
r.GetRect( 4, 4, out ); // rect found ({0,0,4,4} for …Run Code Online (Sandbox Code Playgroud) 我有以下代码片段:
class A
{
public:
A() : x_(0), y_(0) {}
A(int x, int y) : x_(x), y_(y) {}
template<class T>
A(const T &rhs) : x_(rhs.x_), y_(rhs.y_)
{
}
int x_, y_;
};
class B
{
public:
B() {}
operator A() const { return A(c[0],c[1]); }
int c[2];
};
void f()
{
B b;
(A)b; // << here the error appears, compiler tries to use
// template<class T> A(const T &rhs)
}
Run Code Online (Sandbox Code Playgroud)
为什么编译器使用A的构造函数?如何使用B转换运算符A?
我用的是MSVS2010编译器.它给了我这些错误:
main.cpp(9): …Run Code Online (Sandbox Code Playgroud) typedef bool (*my_function_f)(int, double);
typedef bool (__stdcall *my_function_f2)(int, double);
// ^^^^^^^^^
template<class F> class TFunction;
template<class R, class T0, class T1>
class TFunction<R(*)(T0,T1)>
{
typedef R (*func_type)(T0,T1);
};
int main()
{
TFunction<my_function_f> t1; // works on x64 and win32
TFunction<my_function_f2> t2; // works on x64 and doesn't work on win32
return 0;
}
Run Code Online (Sandbox Code Playgroud)
上面的代码在Visual C++ 2010中给出了以下错误:
1>e:\project\orwell\head\multimapwizard\trunk\externals.cpp(49): error C2079: 't2' uses undefined class 'Externals::TFunction<F>'
1> with
1> [
1> F=Externals::my_function_f2
1> ]
Run Code Online (Sandbox Code Playgroud)
正如您可以看到__stdcall修饰符的问题.这是编译器错误吗?
考虑以下代码片段:
template<class T>
std::enable_if_t<std::is_integral<T>::value, bool> func(T value) {
std::cout << "T\n";
return func(static_cast<int64_t>(value));
}
bool func(int64_t value) {
std::cout << "int64_t\n";
return true;
}
int main() {
func(1);
}
Run Code Online (Sandbox Code Playgroud)
它导致无限递归。但是,交换这两个函数的定义顺序(如果bool func(int64_t value)在模板一之前定义)有助于避免此问题。
这是为什么?函数重载的顺序重要吗?
考虑以下代码片段:
class MyClass
{
private:
struct PrivateClass
{
struct SubStruct;
};
public:
struct PrivateClass::SubStruct {};
private:
PrivateClass::SubStruct member;
};
Run Code Online (Sandbox Code Playgroud)
MSVC和gcc编译此代码没有任何错误。但是,clang会产生以下错误:
<source>:10:26: error: non-friend class member 'SubStruct' cannot have a qualified name
struct PrivateClass::SubStruct {};
Run Code Online (Sandbox Code Playgroud)
那么,谁是对的?这是叮当声的错误吗?
std::optional有以下构造函数:
template < class U = T >
constexpr optional( U&& value );
Run Code Online (Sandbox Code Playgroud)
这里的问题是:为什么模板参数U默认为 type T?如果简单地将构造函数更改为以下内容会发生什么:
template < class U /* = T */>
constexpr optional( U&& value );
Run Code Online (Sandbox Code Playgroud)